let express = require('express');
let router = express.Router();

const passport = require('../../config/lib/passport');
const jwt = require("jsonwebtoken");

const SendEmail = require('../../config/lib/email');
let UserService = require('../services/UserService');

router.get('/', (req, res, next) => {
    res.send({
        code: 200,
        data: null,
        msg: '用户接口请求成功'
    })
});

// 登录
router.post('/signin', (req, res, next) => {
    let param = req.body;
    let data = {
        code: 100,
        data: null,
        msg: ''
    };
    if(!param.name) {
        data.msg = '请输入用户名';
        res.send(data);
        return;
    }
    if(!param.password) {
        data.msg = '请输入密码';
        res.send(data);
        return;
    }
    if(param.password.length < 4) {
        data.msg = '密码长度不能小于4';
        res.send(data);
        return;
    }
    passport.authenticate('local', async (user, info) => {
        if(user) {
            let data = await UserService.recordIP(req, user.id);
            let result = $utils._formmat_send_data({data});

            if(result.code == 200) {
                user['dataValues'].token = jwt.sign({ name: user.name }, $config._sk);
                // req.session[user['dataValues'].token] = user.name;
                
                $client._put(user['dataValues'].token, JSON.stringify({
                    name: user.name,
                    status: user.status,
                    role_id: user.role.id
                }));

                result.data = user;
            }
            res.send(result);
        }else{
            res.send({
                code: 422,
                data: null,
                msg: info.message
            })
        }
    })(req, res, next)
});
// 登出
router.post('/signout', (req, res, next) => {
    $client._remove(req.headers['x-access-token']);
    res.send({
        code: 200,
        data: null,
        msg: '退出成功'
    })
})
// 列表
router.get('/list', async ctx => {
    let req = ctx.query;

    let data = await UserService.getUserList(req, ctx.next);
    ctx.res.send($utils._formmat_send_data({data}));
})
// 新增
router.post('/create', async ctx => {
    let param = ctx.body;

    let data = {
        code: 100,
        data: null,
        msg: ''
    }
    if(!param.name) {
        data.msg = '请输入用户名';
        ctx.res.send(data);
        return;
    }
    if(!/^([a-zA-Z]|[0-9])(\w|\-)+@miao+\.cn$/.test(param.name)) {
        data.msg = '请输入正确的邮箱格式';
        ctx.res.send(data);
        return;
    }
    if(!param.part_id) {
        data.msg = '请选择部门';
        ctx.res.send(data);
        return;
    }
    let result = await UserService.register(param);
    let response = {}, user = {};
    if(typeof result === 'string') {
        response =  $utils._formmat_send_data({data: result, changeCount: true});
    }else{
        user = await result.user;
        response =  $utils._formmat_send_data({data:　user, changeCount: true});
    }
    if(response.code === 200) {
        SendEmail([user.name], 'pwd', {pwd: result.password})
        .then(res => {
            if(typeof res === 'string') {
                ctx.res.send($utils._formmat_send_data({data: res, changeCount: true}));
            }else{
                ctx.res.send(response);
            }
        })
        .catch(err => {
            console.log('邮件发送失败: ', user.name, result.password);
            ctx.res.send({
                code: 100,
                msg: '邮件发送失败'
            });
        })
    }else{
        ctx.res.send(response);
    }
})
// 启用
router.post('/enable/:id', async ctx => {
    let data = await UserService.changeUserStatus(ctx.params, 0);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})
// 禁用
router.post('/disable/:id', async ctx => {
    let data = await UserService.changeUserStatus(ctx.params, 1);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})
// 删除
router.post('/delete/:id', async ctx => {
    let data = await UserService.deleteUser(ctx.params);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})
// 查询
router.get('/findUserByName', async ctx => {
    let data = await UserService.findUserByName(ctx.params);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})

module.exports = router;
